import axios, { type Method } from 'axios'
import { getToken } from './auth'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import router from '@/router'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000,
})

service.interceptors.request.use(
  config => {
    // 携带token
    const token = getToken()
    if(token){
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 判断401
    if(error.response.status === 401){
      // 跳转到登录页
      router.push('/login')
      const store = useUserStore()
      store.setToken('')
      ElMessage({
        message:'登录过期，请重新登录',
        type:'error'
      })
    }else{
      ElMessage(error.response.data.msg)
    }
    return Promise.reject(error)
  },
)
// 返回的数据
type Data<T> ={
  code:number,
  data:T,
  message:string
}
// 封装请求方法,只需穿url和方法和根据请求方法传参数
const request = <T> (url:string,method:Method='GET',params?:object)=>{
  return service.request<T,Data<T>>({
    url,
    method,
    // 判断传入的method决定params传给请求的data还是params
    [method.toLowerCase()==='get'?'params':'data']:params
  })
}
export { request,service }
